package com.example.base.adapter.holder

import android.util.SparseArray
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.example.base.adapter.listener.OnItemTouchEventListener
import com.example.base.adapter.selector.ISelectableHolder

open class RVHolder(itemView: View) : RecyclerView.ViewHolder(itemView), ISelectableHolder {

    private var activated: Boolean = false
    private var canSelect = true
    val reusedViews = SparseArray<View>()
    var onItemTouchEventListener: OnItemTouchEventListener? = null
    private val clickItemChild: MutableList<Int> = arrayListOf()

    init {
        itemView.setOnClickListener {
            onItemTouchEventListener?.onItemClick(itemView, adapterPosition)
        }
        itemView.setOnLongClickListener {
            return@setOnLongClickListener onItemTouchEventListener?.onItemLongClick(
                itemView,
                adapterPosition
            ) == true
        }
    }

    override fun setSelectable(selectable: Boolean) {
        canSelect = selectable
    }

    override fun isSelectable(): Boolean {
        return canSelect
    }

    override fun setActivated(activated: Boolean) {
        this.activated = activated
        itemView.isSelected = activated
    }

    override fun isActivated(): Boolean {
        return activated
    }

    /**
     * 通过控件的Id获取对应的控件，如果没有则加入mViews，则从item根控件中查找并保存到mViews中
     *
     * @param viewId  视图ID
     * @return 返回view
     */
    inline fun <reified T : View> getView(viewId: Int): T {
        val view = reusedViews.get(viewId)
        if (view != null && view is T) return view
        val foundView = itemView.findViewById<T>(viewId)
        reusedViews.put(viewId, foundView)
        return foundView
    }

    fun addClickItemChild(childId: Int) {
        getView<View>(childId).setOnClickListener {
            onItemTouchEventListener?.onItemChildClick(it, adapterPosition)
        }
        clickItemChild.add(childId)
    }

    fun removeClickItemChild(childId: Int) {
        getView<View>(childId).setOnClickListener(null)
        clickItemChild.remove(childId)
    }

}

